/*
 * @(#)FreeMarkerEngine.java
 * 2011-8-14 下午12:03:43
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.common.freemarker;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import org.apache.commons.io.FileUtils;

import com.qyxx.platform.common.utils.template.TemplateConfig;

import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateHashModel;
import freemarker.template.TemplateModelException;

/**
 * FreeMarker通用类
 * @author YB
 * @version 1.0
 * @since 1.6 2011-8-14 下午12:03:43
 */

public class FreeMarkerEngine {

	private Configuration freeMarkerConfiguration;
	
	private String templatePath;
	
	public FreeMarkerEngine() {
		this.templatePath = TemplateConfig.LOADPATH;
	}
	
	public FreeMarkerEngine(String templatePath) {
		this.templatePath = templatePath;
	}
	
   public Configuration initEngine() throws TemplateModelException {
		freeMarkerConfiguration = new Configuration();
		freeMarkerConfiguration
				.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);
		//String templatePath = "E:/javasoft/jiawasoft/jiawasoft-gsweb/src/main/resources/template/gsc/";
		try {
			// TODO 换成spring读
			// templatePath = PublishUtils.getResource().getTemplatePath();
		//templatePath = TemplateConfig.LOADPATH;
			freeMarkerConfiguration.setDirectoryForTemplateLoading(new File(
					templatePath));
			freeMarkerConfiguration.setDefaultEncoding(TemplateConfig.DEFAULTENCODING);
		} catch (IOException e) {
			System.out.println("初始化FreeMarker模板目录:" + templatePath + " 异常。");
			e.printStackTrace();
		}
		BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
		TemplateHashModel staticModels = wrapper.getStaticModels();
		TemplateHashModel stringUtilsStatics = (TemplateHashModel) staticModels
				.get("org.apache.commons.lang.StringUtils");
		TemplateHashModel numberUtilsStatics = (TemplateHashModel) staticModels
				.get("org.apache.commons.lang.math.NumberUtils");
		freeMarkerConfiguration.setSharedVariable("StringUtils",
				stringUtilsStatics);
		freeMarkerConfiguration.setSharedVariable("NumberUtils",
				numberUtilsStatics);
		return freeMarkerConfiguration;
	}

	/**
	 * 输出到文件
	 * 
	 * @param template
	 *            ftl模版文件
	 * @param model
	 *            ftl要用到的动态内容
	 * @param saveFilePath
	 *            文件保存路径
	 * @param encoding
	 *            编码
	 * @throws IOException
	 * @throws TemplateException
	 */
	public void create(String template, Map<?,?> model, String saveFilePath,
			String encoding) throws IOException, TemplateException {
		String contentOut = this.render(template, model);
		FileUtils.writeStringToFile(new File(saveFilePath), contentOut, encoding);
/*		// 对文件加锁
		FileOutputStream outputStream = new FileOutputStream(f);
		FileChannel channel = outputStream.getChannel();
		FileLock lock = channel.tryLock(); // 加锁
		Writer out = new BufferedWriter(new OutputStreamWriter(outputStream,
				encoding));

		out.append(contentOut);

		out.flush();
		lock.release();// 解锁
		outputStream.close();
		out.close();
		//System.out.println("成功生成文件：{}" + saveFilePath);
*/		
	}

	public String render(String templatePath, Map model)
			throws TemplateException, IOException {
		initEngine();
		Template template = freeMarkerConfiguration.getTemplate(templatePath);
		Writer out = new StringWriter();
		template.process(model, out);
		return out.toString();
	}

}
